package it.sd.wdc.spider.executer.parser;

import it.sd.utility.RegExpTokenizer2;
import it.sd.wdc.spider.htmlbrowser.HttpUtility;
import it.sd.wdc.spider.repository.template.SpiderNodeTemplate;

import java.util.Iterator;
import java.util.LinkedList;

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class SpiderParser {

	private SpiderNodeTemplate templateRoot =  null;
	private String buffer = null;
	private Document document = null;

  public SpiderParser(SpiderNodeTemplate template, String buffer) throws Exception {
    this.document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    this.templateRoot = template;
    this.buffer = buffer;
  }
  
  public Document parse() throws Exception {
    
	  // l'elemento di root � sempre vuoto
    Element element = document.createElement(templateRoot.getName()); 
    document.appendChild(element);
    
    elaboroFigli(element, templateRoot, buffer);
    
    return document;
  }
  
  private void elaboroFigli(Element padre, SpiderNodeTemplate template, String valore) {

	  // aggiungo i figli
	  for (@SuppressWarnings("unchecked")
	Iterator<SpiderNodeTemplate> iterator = 
			  (Iterator<SpiderNodeTemplate>) template.iterateFigli(); 
			  iterator.hasNext();) {
		  SpiderNodeTemplate node= iterator.next();
		  addFiglio(padre, node, valore);
	  }
	  
  }
  
  private void addFiglio(Element padre, SpiderNodeTemplate template, String valore) {

	  LinkedList<String> elencoValori = parse(valore, template.getRegexp(), template.getItem());

	  for (Iterator<String> iterator = elencoValori.iterator(); iterator.hasNext();) {
		  String string = iterator.next();
		  Element e = document.createElement(template.getName());
		  if (!template.isIgnoreContent()) {
			  String v = string;
			  if (template.isRemoveTag()) {
				  v = HttpUtility.removeTag(v);
			  }
			  if (template.isTrimSpace()) {
				  v = HttpUtility.trimSpace(v);
			  }
			  e.setTextContent(v);
		  }
		  padre.appendChild(e);
		  
		  elaboroFigli(e, template, string);
	  }
	  
  }

  private LinkedList<String> parse(String valore, String regexp, int item) {
	  LinkedList<String> elenco = new LinkedList<String>();
	  
	  if ((regexp==null) || (regexp.trim().length()==0) ) {
		  elenco.add(valore);
	  } else {
		  RegExpTokenizer2 re = new RegExpTokenizer2(valore, regexp);
		  int i = 1;
		  while (re.hasNext()) {
			  String s = re.next();
			  if (item!=0) {
				  if (item == i) {
					  elenco.add(s);
					  break;
				  }
			  } else {
				  elenco.add(s);
			  }
			  i++;
		  }
	  }
	  
	  return elenco;
  }
  

}
